/**
 * SideBar.js
 * Provides the sidebar navigation component for the Virtual Bank System
 */

class SideBar {
  constructor() {
    this.user = null;
    this.balance = {
      balance: 0,
      frozenAmount: 0,
      availableBalance: 0
    };
    this.activeMenuItem = '';
    this.collapsed = false;
  }

  /**
   * Initialize the sidebar
   */
  init(activeMenuItem = '') {
    this.activeMenuItem = activeMenuItem;
    this.loadUserInfo();
    this.loadAccountBalance();
    this.render();
    this.bindEvents();
  }

  /**
   * Load user information
   */
  loadUserInfo() {
    // Try to get user info from localStorage
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      this.user = JSON.parse(userInfo);
    }
  }

  /**
   * Load account balance information
   */
  loadAccountBalance() {
    const token = this.getAuthToken();
    
    if (!token) return;

    fetch('/api/account/balance', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      if (data.code === 0 && data.data) {
        this.balance = data.data;
        this.updateBalanceDisplay();
      }
    })
    .catch(error => {
      console.error('Error loading account balance:', error);
    });
  }

  /**
   * Get authentication token from cookies
   */
  getAuthToken() {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.startsWith('virtualbank_token=')) {
        return cookie.substring('virtualbank_token='.length, cookie.length);
      }
    }
    return null;
  }

  /**
   * Render the sidebar
   */
  render() {
    const sidebarElement = document.getElementById('sidebar');
    
    if (!sidebarElement) {
      console.error('Sidebar element not found');
      return;
    }

    sidebarElement.className = `sidebar${this.collapsed ? ' collapsed' : ''}`;
    
    sidebarElement.innerHTML = `
      <div class="sidebar-header">
        <h3>${this.collapsed ? 'VB' : 'Virtual Bank'}</h3>
      </div>
      <div class="sidebar-account-info">
        ${this.collapsed ? '' : '<div class="sidebar-welcome">Welcome, <span id="sidebar-username">User</span></div>'}
        <div class="sidebar-account-balance">
          <div class="balance-label">${this.collapsed ? '' : '可用余额'}</div>
          <div class="balance-amount" id="available-balance">¥0.00</div>
        </div>
      </div>
      <ul class="sidebar-menu">
        <li class="sidebar-menu-item ${this.activeMenuItem === 'dashboard' ? 'active' : ''}" data-page="dashboard">
          <i class="sidebar-menu-icon fas fa-home"></i>
          ${this.collapsed ? '' : '<span>首页</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'profile' ? 'active' : ''}" data-page="profile">
          <i class="sidebar-menu-icon fas fa-user"></i>
          ${this.collapsed ? '' : '<span>账户管理</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'transfer' ? 'active' : ''}" data-page="transfer">
          <i class="sidebar-menu-icon fas fa-exchange-alt"></i>
          ${this.collapsed ? '' : '<span>转账</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'transactions' ? 'active' : ''}" data-page="transactions">
          <i class="sidebar-menu-icon fas fa-list"></i>
          ${this.collapsed ? '' : '<span>交易记录</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'bankcards' ? 'active' : ''}" data-page="bankcards">
          <i class="sidebar-menu-icon fas fa-credit-card"></i>
          ${this.collapsed ? '' : '<span>银行卡</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'loans' ? 'active' : ''}" data-page="loans">
          <i class="sidebar-menu-icon fas fa-money-bill-wave"></i>
          ${this.collapsed ? '' : '<span>贷款</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'financial' ? 'active' : ''}" data-page="financial">
          <i class="sidebar-menu-icon fas fa-chart-line"></i>
          ${this.collapsed ? '' : '<span>理财产品</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'notifications' ? 'active' : ''}" data-page="notifications">
          <i class="sidebar-menu-icon fas fa-bell"></i>
          ${this.collapsed ? '' : '<span>消息中心</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'recharge' ? 'active' : ''}" data-page="recharge">
          <i class="sidebar-menu-icon fas fa-plus-circle"></i>
          ${this.collapsed ? '' : '<span>充值</span>'}
        </li>
        <li class="sidebar-menu-item ${this.activeMenuItem === 'withdraw' ? 'active' : ''}" data-page="withdraw">
          <i class="sidebar-menu-icon fas fa-minus-circle"></i>
          ${this.collapsed ? '' : '<span>提现</span>'}
        </li>
      </ul>
      <div class="sidebar-toggle" id="sidebar-toggle">
        <i class="fas ${this.collapsed ? 'fa-angle-right' : 'fa-angle-left'}"></i>
      </div>
    `;

    this.updateUserDisplay();
    this.updateBalanceDisplay();
  }

  /**
   * Update user display with current user info
   */
  updateUserDisplay() {
    const usernameElement = document.getElementById('sidebar-username');
    
    if (this.user && usernameElement) {
      usernameElement.textContent = this.user.username || 'User';
    }
  }

  /**
   * Update balance display
   */
  updateBalanceDisplay() {
    const balanceElement = document.getElementById('available-balance');
    
    if (balanceElement) {
      balanceElement.textContent = `¥${this.formatMoney(this.balance.availableBalance)}`;
    }
  }

  /**
   * Format money amount with 2 decimal places
   */
  formatMoney(amount) {
    return parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  }

  /**
   * Bind events to sidebar elements
   */
  bindEvents() {
    // Toggle sidebar collapse state
    const sidebarToggle = document.getElementById('sidebar-toggle');
    if (sidebarToggle) {
      sidebarToggle.addEventListener('click', () => {
        this.collapsed = !this.collapsed;
        this.render();
        
        // Update content margin
        const contentElement = document.querySelector('.content');
        if (contentElement) {
          if (this.collapsed) {
            contentElement.classList.add('sidebar-collapsed');
          } else {
            contentElement.classList.remove('sidebar-collapsed');
          }
        }
      });
    }

    // Menu item clicks
    const menuItems = document.querySelectorAll('.sidebar-menu-item');
    menuItems.forEach(item => {
      item.addEventListener('click', () => {
        const page = item.getAttribute('data-page');
        this.navigateToPage(page);
      });
    });
  }

  /**
   * Navigate to a page
   */
  navigateToPage(page) {
    switch (page) {
      case 'dashboard':
        window.location.href = '/index.html';
        break;
      case 'profile':
        window.location.href = '/profile.html';
        break;
      case 'transfer':
        window.location.href = '/transfer.html';
        break;
      case 'transactions':
        window.location.href = '/transactions.html';
        break;
      case 'bankcards':
        window.location.href = '/bankcards.html';
        break;
      case 'loans':
        window.location.href = '/loans.html';
        break;
      case 'financial':
        window.location.href = '/financial.html';
        break;
      case 'notifications':
        window.location.href = '/notifications.html';
        break;
      case 'recharge':
        window.location.href = '/recharge.html';
        break;
      case 'withdraw':
        window.location.href = '/withdraw.html';
        break;
      default:
        window.location.href = '/index.html';
    }
  }
}

// Export for use in other files
window.SideBar = SideBar;
